﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using OConf.API.hub;
using OConf.IBLL;
using OConf.Model.Common;
using OConf.Model.RequestInput.CNameSpace;
using OConf.Model.RequestInput.ConfigInfo;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace OConf.API.Controllers
{
    [Authorize]
    [Route("api/[Controller]/[Action]")]
    [ApiController]
    public class CNameSpaceController : ControllerBase
    {
        private readonly ICNameSpaceBLL _cNameSpaceBLL;
        private readonly IHubContext<ChatHub> _hubContext;

        public CNameSpaceController(ICNameSpaceBLL cNameSpaceBLL, IHubContext<ChatHub> hubContext)
        {
            _cNameSpaceBLL = cNameSpaceBLL;
            _hubContext = hubContext;
        }

        /// <summary>
        /// 新增命名空间信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ReturnData<bool> AddCNameSpace([FromBody] AddCNameSpaceInput input)
        {
            return _cNameSpaceBLL.AddCNameSpace(input);
        }

        /// <summary>
        /// 删除命名空间
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ReturnData<bool> DeleteCNameSpace([FromBody] DeleteCNameSpaceInput input)
        {
            return _cNameSpaceBLL.DeleteCNameSpace(input);
        }

        /// <summary>
        /// 获取命名空间列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public ReturnData<List<CNameSpaceModel>> GetCNameSpaceList([FromQuery] GetNameSpaceInput input)
        {
            return _cNameSpaceBLL.GetCNameSpaceList(input);
        }

        /// <summary>
        /// 获取单个CNameSpace信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public ReturnData<CNameSpaceModel> GetCNameSpaceModel([FromQuery] GetNameSpaceDetailInput input)
        {
            return _cNameSpaceBLL.GetCNameSpaceModel(input);
        }

        /// <summary>
        /// 发布配置信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ReturnData<bool>> PublishConfigInfo([FromBody] PublishConfigInput input)
        {
            var result = _cNameSpaceBLL.PublishConfigInfo(input);

            if (result.Code == 200 && result.Data != null)
            {
                await _hubContext.Clients.User(result.Data.ProjectName).SendAsync("ReceiveConfig", result.Data);

                return ReturnDataHelper<bool>.Success("操作成功", true);
            }
            else
            {
                return ReturnDataHelper<bool>.DiyResult(result.Code, result.Msg, false);
            }
        }
    }
}